# -*- coding: utf-8 -*-
# @Time    : 2021/11/17 5:39 下午
# @Author  : zlt
# @FileName: util_email.py
# @Software: PyCharm

import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


def send_email(from_addr,pwd,to_addrs,m_subject,m_content,m_appendix):

    #-------------准备邮件中的附件-------------
    #图片文件处理
    # imageFile = '1.png'
    # imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    # imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)

    #pdf文件处理
    # pdfFile = '算法设计与分析基础第3版PDF.pdf'
    # pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
    # pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)

    #压缩包文件处理
    zipFile = m_appendix
    zipApart = MIMEApplication(open(zipFile, 'rb').read())
    zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)

    # ---------------------设置email信息-------------------
    # 设置邮件内容
    textApart = MIMEText(m_content)
    #添加邮件中的内容
    m = MIMEMultipart()
    m.attach(textApart)
    # m.attach(imageApart)
    # m.attach(pdfApart)
    m.attach(zipApart)
    m["Subject"] = m_subject

    #-----------开始发送邮件------------
    try:
        #设置邮件发送服务地址
        server = smtplib.SMTP('smtp.yunlsp.com')
        server.login(user=from_addr,password=pwd)
        server.sendmail(from_addr,to_addrs,m.as_string())
        print("send success")
        server.quit()
    except smtplib.SMTPException as e:
        print(e)




# if __name__ == '__main__':
#     fromaddr = 'allen.zhang@yunlsp.com'
#     password = 'drH4jgKMyUgyNX5m'
#     subject = "测试报告邮件"
#     toaddrs = ['851037167@qq.com']
#     content = 'hello, this is email content.'
#     zipFile = '/Users/zhanglvtian/CrawlerProject/results.zip'
#     send_email(from_addr=fromaddr,pwd=password,to_addrs=toaddrs,m_subject=subject,m_content=content,m_appendix=zipFile)






